import {
  Injectable,
  CanActivate,
  ExecutionContext,
  UnauthorizedException,
} from '@nestjs/common';
import { Reflector } from '@nestjs/core';

@Injectable()
export class RolesGuard implements CanActivate {
  constructor(private _reflector: Reflector) {}

  canActivate(context: ExecutionContext): boolean {
    // 获取自定义装饰器Roles传递的角色代码
    const roles = this._reflector.get<string[]>('roles', context.getHandler());
    // 没有传递Roles默认为通过token校验的都可以用
    if (!roles) {
      return true;
    }
    const request = context.switchToHttp().getRequest();
    const user = request.user;
    // TODO 通过判断该用户所拥有的权限来判断该用户是否能够访问该接口
    // 无权限 抛出401
    if (!user) throw new UnauthorizedException({ errorType: 'permissions' });
    return true;
  }
}
